package com.android.place360.place_search_result;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import com.android.place360.R;
import com.android.place360.appsettings.SharePreference_Setting;
import com.android.place360.current_location.MyLocationListener;
import com.android.place360.current_location.MyLocationManager;
import com.android.place360.database.Catalog;
import com.android.place360.google_places.PlaceRequest;
import com.android.place360.google_places.PlaceResponse;
import com.android.place360.google_places.PlaceResult;
import com.android.place360.place_detail.DetailRequest;
import com.android.place360.place_detail.DetailResponse;
import com.android.place360.place_detail.DetailResult;

import android.app.Activity;
import android.app.ProgressDialog;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class PlaceResultActivity extends Activity implements Runnable {

	public static final int MSG_PLACE_SEARCH = 0;
	public static final int MSG_PLACE_DETAIL = 1;
	public static final int MSG_FINISH = 2;

	ListResultAdapter adapter;
	private ListView list;
	private ProgressDialog progressDialog;
	private static ArrayList<PlaceItem> lstPlace;
	private Thread thread;
	private static Catalog catalog;
	private boolean replay = false;

	private int count;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_result);

		list = (ListView) findViewById(R.id.listResults);

		Bundle bundle = getIntent().getExtras();
		Catalog newCatalog = (Catalog) bundle.getSerializable("CATALOG");
		if (catalog != null
				&& newCatalog.getSearch_key() == catalog.getSearch_key())
			replay = true;
		else
			catalog = newCatalog;

		TextView txtTitle = (TextView) findViewById(R.id.layout_result_txtTitle);
		txtTitle.setText(catalog.getName());

		ImageButton btnSort = (ImageButton) findViewById(R.id.result_layout_btnSort);
		btnSort.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Collections.sort(lstPlace);

				adapter.notifyDataSetChanged();
			}
		});

		progressDialog = ProgressDialog.show(this, "",
				getString(R.string.progress_load_locations));
		progressDialog.setCancelable(true);
		thread = new Thread(this);
		thread.start();

	}

	@Override
	public void run() {

		// If research the previous key
		if (lstPlace == null || replay == false) {
			Log.i("place360", String.valueOf(new Date().getSeconds()));

			final PlaceRequest placeRequest = new PlaceRequest();
			placeRequest.setKey(getString(R.string.google_place_api_key));
			placeRequest.setLanguage(SharePreference_Setting
					.getLanguage(getApplicationContext()));
			placeRequest
					.setLocation(MyLocationListener.myCurrentLocation
							.getLatitude()
							+ ","
							+ MyLocationListener.myCurrentLocation
									.getLongitude());
			placeRequest.setName(catalog.getSearch_key());
			placeRequest.setRadius(5000);
			placeRequest.setSensor(true);

			PlaceResponse place = placeRequest.getResponse();

			lstPlace = new ArrayList<PlaceItem>();

			int numberOfResults = SharePreference_Setting
					.getNumberOfResults(getApplicationContext());
			if (numberOfResults > place.getResults().length)
				numberOfResults = place.getResults().length;

			for (int i = 0; i < numberOfResults; i++) {
				final PlaceItem item = new PlaceItem();
				final PlaceResult pResult = place.getResults()[i];
				item.setPlaceResult(pResult);

				// compute distance
				Location loc = new Location(MyLocationManager.provider);
				loc.setLatitude(pResult.getGeometry().getLocation().getLat());
				loc.setLongitude(pResult.getGeometry().getLocation().getLng());
				item.setDistance((int) Math
						.round(MyLocationListener.myCurrentLocation
								.distanceTo(loc)));

				

//				DetailRequest detailRequest = new DetailRequest();
//				detailRequest.setKey(getString(R.string.google_place_api_key));
//				detailRequest.setLanguage("vi");
//				detailRequest.setReference(pResult.getReference());
//				detailRequest.setSensor(true);
//				DetailResponse detail = detailRequest.getResponse();
//				Log.i("place360", "END " + String.valueOf(new Date().getSeconds()));
				
				//dResult = detailRequest.getResponse().getResult();
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						
						DetailRequest detailRequest = new DetailRequest();
						detailRequest.setKey(getString(R.string.google_place_api_key));
						detailRequest.setLanguage("vi");
						detailRequest.setReference(pResult.getReference());
						detailRequest.setSensor(true);
						DetailResponse detail = detailRequest.getResponse();
						Log.i("place360", "END " + String.valueOf(new Date().getSeconds()));
						DetailResult dResult = detailRequest.getResponse().getResult();
						item.setDetailResult(dResult);
						handler.sendEmptyMessage(PlaceResultActivity.MSG_PLACE_DETAIL);
						
					}
				}).start();
//				PullTasksThread t = new PullTasksThread(
//						getApplicationContext(), item.getPlaceResult()
//								.getReference(), handler, dResult);
//				t.start();

				//item.setDetailResult(dResult);
				lstPlace.add(item);
			}

			//handler.sendEmptyMessage(MSG_FINISH);

		} else
			handler.sendEmptyMessage(0);

	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_PLACE_SEARCH:

				for (PlaceItem item : lstPlace) {
					PullTasksThread t = new PullTasksThread(
							getApplicationContext(), item.getPlaceResult()
									.getReference(), handler, item
									.getDetailResult());
					t.start();
				}

				break;
			case MSG_PLACE_DETAIL:
				count++;
				if (count == lstPlace.size())
					handler.sendEmptyMessage(MSG_FINISH);
				break;
			case MSG_FINISH:
				adapter = new ListResultAdapter(getApplicationContext(),
						R.layout.custom_list_result, lstPlace);
				list.setAdapter(adapter);
				progressDialog.dismiss();
			}

		}
	};

}
